<?php

function login($username,$password)
{
	$CI =& get_instance();
	$sql = 'select * from users where username = ? and password = ?';
	$user = $CI->db->GetRow($sql,array($username,md5($password)));	
	dbConvert($user);
	if($user['id'])
	{
		if(($user['online']==0) OR (($user['online']==1) && ($user['session_id']==session_id())) OR (($user['online']==1) && (time()-$user['online_time']>600)))
		{
			$CI->session->set_userdata('id',$user['id']);
			set_notify('success','ยินดีต้อนรับเข้าสู่ระบบค่ะ');
			return TRUE;
		}
		else
		{
			set_notify('error','ไม่สามารถล็อคอินซ้อนได้ค่ะ กรุณาลองใหม่อีกครั้ง');
			return FALSE;
		}
	}
	else
	{
		set_notify('error','ชื่อผู้ใช้หรือรหัสผ่านผิดพลาด กรุณาลองใหม่อีกครั้ง');
		return FALSE;
	}
}

function random_password() {

    $chars = "abcdefghijkmnopqrstuvwxyz023456789";

    srand((double)microtime()*1000000);

    $i = 0;

    $pass = '' ;

    while ($i <= 7) {

        $num = rand() % 33;

        $tmp = substr($chars, $num, 1);

        $pass = $pass . $tmp;

        $i++;

    }
    return $pass;
}

function is_login($level = FALSE)
{
	$CI =& get_instance();
	if($level)
	{
		$sql = 'select id from users where id = ? and level_id <= ?';
		$id = $CI->db->GetOne($sql,array($CI->session->userdata('id'),$CI->db->getone('select id from levels where level = ?',$level)));
	}
	else
	{
		$sql = 'select id from users where id = ?';
		$id = $CI->db->GetOne($sql,$CI->session->userdata('id'));
	}
	return ($id) ? true : false;
}

function login_data($field = FALSE)
{
	$CI =& get_instance();
	$field = strtoupper($field);
	$CI->load->model('user/user_model','user');
	return ($field)?$CI->user->get_one($field,$CI->session->userdata('id')):$CI->user->get_row($CI->session->userdata('id'));
}

function level_data($field = FALSE)
{
	$CI =& get_instance();
	$field = strtoupper($field);
	return ($field)?$CI->db->getone('select '.$field.' from levels where id = (select level_id from users where id = '.$CI->session->userdata('id').')' ):$CI->user->getrow('select * from levels where id = (select level_id from users where id = '.$CI->session->userdata('id').')' );
}

function logout()
{
	$CI =& get_instance();
	$data['id'] = $CI->session->userdata('id');
	$data['online'] = 0;
	$CI->load->model('user/user_model','user');
	$CI->user->save($data);
	$CI->session->unset_userdata('id');
}
	
?>